package com.eimf.saf.base.dao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.eimf.saf.base.querycomm.SearchExpression;
import com.eimf.saf.base.util.GenericsUtils;
import com.ibatis.sqlmap.client.SqlMapClient;

/**
 * @author eden 数据存取的基类,后续开发的DAO必须继承此类
 */
public class BaseDao<E> extends SqlMapClientDaoSupport
{
    private final Class<?> entityClass = GenericsUtils.getGenericClass(this.getClass());

    protected String namespace = entityClass.getSimpleName() + "Map";

    public Class<?> getEntityClass()
    {
        return entityClass;
    }

    /*
     * 向父类属性 sqlMapClient注入SqlMapClient对象
     */
    @Autowired
    public void setSuperSqlMapClient(final SqlMapClient sqlMapClient)
    {
        super.setSqlMapClient(sqlMapClient);
    }

    @SuppressWarnings("unchecked")
    public E find(final SearchExpression searchExp)
    {
        return (E) this.getSqlMapClientTemplate().queryForObject(namespace + ".find", searchExp);
    }

    @SuppressWarnings("unchecked")
    public List<E> findList(final SearchExpression searchExp)
    {
        return this.getSqlMapClientTemplate().queryForList(namespace + ".find", searchExp);
    }

    // 是分页查询方法 begin
    @SuppressWarnings("unchecked")
    public List<E> findListToPage(final SearchExpression searchExp)
    {
        return this.getSqlMapClientTemplate().queryForList(namespace + ".findList", searchExp);
    }

    /**
     * 获取总行数
     * 
     * @return
     */
    public int findTotalRows(final SearchExpression searchExpression)
    {
        return (Integer) this.getSqlMapClientTemplate().queryForObject(this.namespace + ".getTotalRows",
                searchExpression);
    }

    // /分页查询方法 end

    public String addData(final E entity)
    {
        return (String) this.getSqlMapClientTemplate().insert(namespace + ".add", entity);
    }

    public void updateData(final E entity)
    {
        this.getSqlMapClientTemplate().update(namespace + ".update", entity);
    }

    public void delData(final E entity)
    {

        this.getSqlMapClientTemplate().delete(namespace + ".delete", entity);
    }

}
